from flask import Flask, request, jsonify, send_from_directory
import os
from client import MCPClient
import asyncio
app = Flask(__name__)
client = MCPClient()
UPLOAD_FOLDER = 'upload_audio'
app.config['TIMEOUT'] = 0
@app.route('/mcpMsg/chat', methods=['POST'])
def chat():
    if not request.is_json:
        return jsonify({'error': 'Content-Type must be application/json'}), 415
    data = request.json
    query = data.get('query')
    if not query:
        return jsonify({'error': 'Missing query parameter'}), 400
    cookie = request.cookies.get('jreapSid')
    if not cookie:
        return jsonify({'error': 'Missing jreapSid cookie'}), 400
    os.environ['FUEL_TOKEN'] = cookie
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    try:
        servers = {
            "server": "server.py"
        }
        loop.run_until_complete(client.connect_to_server(servers))
        response = loop.run_until_complete(client.api_call(query))
        return jsonify({'result': response, 'flag': 'success'})
    finally:
        loop.close()

@app.route('/mcpMsg/login_serve', methods=['get'])
def login_serve():
    cookie = request.cookies.get('jreapSid')
    if not cookie:
        return jsonify({'error': 'Missing jreapSid cookie'}), 400
    os.environ['FUEL_TOKEN'] = cookie
    servers = {
        "server": "server.py"
    }
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    try:
        loop.run_until_complete(client.connect_to_server(servers))
        return jsonify({'result': cookie, 'flag': 'success'})
    finally:
        loop.close()

@app.route('/render_html/<filename>')
def render_html(filename):
    return send_from_directory('render_html', filename)

@app.route('/audio_data/<filename>')
def audio_data(filename):
    return send_from_directory(UPLOAD_FOLDER, filename)


@app.route('/mcpMsg/upload_audio', methods=['POST'])
def upload_audio():
    try:
        # 检查请求中是否包含音频文件
        if 'audio' not in request.files:
            return 'No audio file provided', 400
        audio_file = request.files['audio']
        # 检查文件名是否为空
        if audio_file.filename == '':
            return 'No selected file', 400
        # 保存音频文件
        file_path = os.path.join(UPLOAD_FOLDER, audio_file.filename)
        audio_file.save(file_path)
        # UPLOAD_FOLDER 的绝对路径如何获取
        UPLOAD_PATH = os.path.abspath(UPLOAD_FOLDER)
        audio_file_path = os.path.join(UPLOAD_PATH, audio_file.filename)
        audio_text = client.audio_to_text(audio_file_path)
        print("============", audio_text)
        return jsonify({'result': audio_text, 'flag': 'success'})
    except Exception as e:
        return f'Error: {str(e)}', 500
    

async def main():
    app.run(host='0.0.0.0', port=5000)


if __name__ == '__main__':
    asyncio.run(main())